package com.shop.bookstore.controller;

import com.shop.bookstore.entity.Reader;
import com.shop.bookstore.service.ReaderService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/reader")
public class ReaderController {
    @Autowired
    ReaderService readerService;
    @Autowired
    HttpServletRequest request;
    @RequestMapping("/readerList")
    public String readerMain(Model model){
        Object username = request.getSession().getAttribute("username");
        if(username==null){
            return "redirect:/";
        }else{
//            调用service方法查询到商品列表
            List<Reader> readerList = readerService.findAll();
            System.out.println(readerList);
//            将查询结果用model锁定
            model.addAttribute("data",readerList);
            model.addAttribute("username",username);
//            return视图
            return "reader/readerlist";}
    }
    //    签单实现增加删除更改这些操作在这处理
    @RequestMapping("/readerAdd")
    public String readerAdd(Model model){
        Object username = request.getSession().getAttribute("username");
        if(username==null){
            return "redirect:/";
        }else{
            model.addAttribute("username",username);
            return "reader/readerAdd";
        }

    }

    @RequestMapping("/readerAddProcess")
    public String bookAddProcess(@RequestParam String readername, @RequestParam String idCard,
                                 @RequestParam String borrow_books, @RequestParam String timeout_record
                                 ){
//      组装一个book实体对象
        Reader reader = new Reader(null,readername,Integer.valueOf(idCard),borrow_books,Integer.valueOf(timeout_record));
//        调用service的add方法给数据库
        if (readerService.add(reader)==1){
//        如果返回ok，那么就进入商品管理首页
            return "redirect:/reader/readerList";
        }else{
            return "redirect:/reader/readerList";
        }
    }
//    处理更新商品，首先要给出一个页面显示该条记录的数据
    @RequestMapping("/readerUpdate")
    public String readerUpdate(Model model,@RequestParam String id){
        Object username = request.getSession().getAttribute("username");
        if(username==null){
            return "redirect:/";
        }else{
//        首先基于id查询出来该id记录里的所有数据信息
            Reader reader=new Reader();
            reader.setId(Integer.valueOf(id));
//        调用service方法查询出来该记录的数据信息
            Reader readerDB = readerService.findOne(reader);
//        2.将这些数据信息返回给视图
            model.addAttribute("data",readerDB);
            model.addAttribute("username",username);
//        3.返回视图文件
            return "reader/readerUpdate";}
    }
}
